package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;

@Service
@Slf4j
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Override
    public ShoppingCart add(ShoppingCart shoppingCart, Long userId) {
  /*
 ShoppingCart(id=null, name=王老吉, userId=null, dishId=1413384757047271425,setmealId=null, dishFlavor=常温,
  number=null, amount=5, image=2022/10/10/00874a5e-0df2-446b-8f69-a30eb7d88ee8.png, createTime=null)
  */

        log.info("userId:==={}",userId);
        Long setmealId = shoppingCart.getSetmealId();
        Long dishId = shoppingCart.getDishId();
        LambdaQueryWrapper<ShoppingCart> lqw =new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,userId);
        if (dishId == null) {
            //套餐添加
            shoppingCart.setSetmealId(setmealId);
            lqw.eq(setmealId != null, ShoppingCart::getSetmealId, setmealId);
        } else {
            //* 菜品添加
            shoppingCart.setDishId(dishId);
            lqw.eq(dishId != null, ShoppingCart::getDishId, dishId);
        }
        ShoppingCart shopping= this.getOne(lqw);
        if(shopping==null){
            shoppingCart.setNumber(1);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            this.save(shoppingCart);
            shopping=shoppingCart;
        }else{
            shopping.setNumber(shopping.getNumber()+1);
            this.updateById(shopping);
        }

        return shopping;
    }

}
